package com.ziyuan.interceptors;

import cn.hutool.core.convert.Convert;
import cn.hutool.jwt.JWT;
import cn.hutool.jwt.JWTPayload;
import cn.hutool.jwt.JWTUtil;
import com.ziyuan.utils.ThreadLocalUtil;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import java.util.HashMap;
import java.util.Map;

@Component
public class interceptors implements HandlerInterceptor {
    private static final Logger log = LoggerFactory.getLogger(interceptors.class);

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String string = request.getHeader("Authorization");
//        try {
//            boolean stringObjectMap = JWTUtil.verify(string,"claims".getBytes());
//
//             return stringObjectMap;
//
//        } catch (Exception e) {
//            response.setStatus(401);
//
//            return false;
//        }
//
//    }
        boolean verify = JWTUtil.verify(string, "claims".getBytes());
        JWT jwt = JWTUtil.parseToken(string);
        String username = Convert.toStr(jwt.getPayload().getClaim("username")) ;
        String id = Convert.toStr(jwt.getPayload().getClaim("id")) ;
        Map<String,String> map = new HashMap<>();
        map.put("username",username);
        map.put("id",id);
        log.info("map集合为;{}", map);
        ThreadLocalUtil.set(map);

        if (verify) {
            return true;
        } else {
            response.setStatus(401);
            return false;
        }
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

        ThreadLocalUtil.remove();
    }
}
